const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const app = express();

// 允许所有跨源请求
app.use(cors());

// 使用body-parser中间件解析JSON格式的请求体
app.use(bodyParser.json());

// 数据库配置
const dbConfig = {
  host: '127.0.0.1',
  user: 'root',
  password: '123456',
  database: 'tech_box'
};

// 创建数据库连接池
const pool = mysql.createPool(dbConfig);

// JWT 密钥
const JWT_SECRET = '%4mO&lSG1VNEX9vVGgMo@ZWcSm7xL8GnadE8@j^&hmgVXg6HzAIV!b86kyQdCaR3';

// 用户登录
app.post('/login', (req, res) => {
  const { username, password } = req.body;
  pool.query('SELECT * FROM users WHERE username = ?', [username], (error, results) => {
    if (error) {
      return res.status(500).json({ error: error.message });
    }
    if (results.length === 0 || results[0].password !== password) {
      return res.status(401).json({ error: 'Authentication failed' });
    }
    const token = jwt.sign({ id: results[0].id }, JWT_SECRET);
    res.json({ token: token });
  });
});

// 中间件：验证 JWT
const authenticateJWT = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];
  if (token == null) return res.sendStatus(401);

  jwt.verify(token, JWT_SECRET, (err, user) => {
    if (err) return res.sendStatus(403);
    req.user = user;
    next();
  });
};

// 发布新闻接口
app.post('/publish', authenticateJWT, (req, res) => {
  const { image_path, title, summary, publish_date, source, body } = req.body;
  //const formattedDate = new Date(publish_date).toISOString();
  //console.log("title="+title);
  pool.query('INSERT INTO news_content (image_path, title, summary, publish_date, source, body) VALUES (?, ?, ?, ?, ?, ?)', 
             [image_path, title, summary, publish_date, source, body], 
             (error, results) => {
    if (error) {
      return res.status(500).json({ error: error.message });
    }
    res.json({ message: 'News published successfully' });
  });
});

// 删除新闻
app.post('/delete', authenticateJWT, (req, res) => {
  const { ids } = req.body;
  if (!ids || ids.length === 0) {
    return res.status(400).json({ error: 'No news IDs provided' });
  }
  const query = 'DELETE FROM news_content WHERE id IN (?)';
  pool.query(query, [ids], (error, results) => {
    if (error) {
      return res.status(500).json({ error: error.message });
    }
    res.json({ message: 'News deleted successfully' });
  });
});

// POST接口 /news，根据请求的method返回新闻列表或特定新闻详情
app.post('/news', (req, res) => {
  const { method } = req.body; // 解析请求的JSON体

  switch(method) {
    case 'get_news_list':
      // 获取新闻列表，排除content字段
      pool.query('SELECT id, image_path, title, summary, publish_date, source FROM news_content order by publish_date desc', (error, results) => {
        if (error) {
          res.status(500).json({ error: error.message });
        } else {
          res.json(results);
        }
      });
      break;
    case 'get_news_by_id':
      // 获取新闻详情，包含所有字段
      const newsId = req.body.id; // 从请求体获取新闻id
      if (!newsId) {
        return res.status(400).json({ error: 'News ID is required' });
      }
      pool.query('SELECT * FROM news_content WHERE id = ?', [newsId], (error, results) => {
        if (error) {
          res.status(500).json({ error: error.message });
        } else if (results.length === 0) {
          res.status(404).json({ error: 'News not found' });
        } else {
          res.json(results[0]);
        }
      });
      break;
    default:
      // 如果请求的method不正确，返回错误信息
      res.status(400).json({ error: 'Invalid method' });
  }
});

const port = process.env.PORT || 3005;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});